<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Ad extends Admin_Controller {
    private $webmaster_config = 'config';
	private $model_config     = 'ad';
	
	public function __construct(){
        parent::__construct();
		$this->load->library('form_validation');
        $this->load->library('image_lib');
		$this->set_webmaster_config(); //添加后台配置文件
	}
	private function set_webmaster_config(){
		$this->webmaster_config=$this->config->item('webmaster');
	}
		
	public function banner_list(){
		$webmaster_config = $this->webmaster_config;
        $list=$this->data->get_all('ca_ad',"1=1",'*','AId desc');
		$data=array(
			'page_name'			=> 'banner',
            'list'              => $list,
			'webmaster_config'	=> $webmaster_config
		);
		$this->load->view(THEME_PATH.'/ad.php',$data);
	}
	
	public function banner_mod(){
		$aid=(int)$_GET['aid'];	
		$webmaster_config = $this->webmaster_config;
		$item=$this->data->get_one('ca_ad',"aid='$aid'");
		$data=array(
			'page_name'			=> 'banner',
			'webmaster_config'	=> $webmaster_config,
			'aid'				=> $aid,
			'item'				=> $item
		);
		$this->load->view(THEME_PATH.'/ad.php',$data);
	}

	public function banner_mod_action(){
        $webmaster_config = $this->webmaster_config;
		$aid=(int)$this->input->post('aid');
		$this->form_validation->set_rules('page_name-mod', '广告图标题', 'required');
		$this->form_validation->set_rules('pic_count-mod', '广告图数量', 'required');
		$this->form_validation->set_rules('width-mod', '广告图宽度', 'required');
		$this->form_validation->set_rules('height-mod', '广告图高度', 'required');
        !$this->form_validation->run() && e_json(validation_errors(),0);
		($this->input->post('pic_count') > 5) && e_json('最多可以上传5张广告图',0);
        $picpath_ary	  = $this->input->post('mul_upload',true);
        $data             = get_data($this->input->post(),'');
		if($aid){
			$item=$this->data->get_one('ca_ad',"aid='$aid'");
			//upload and resize start
	        $ret_ary     = array();
			for($i=0;$i<$item['pic_count'];$i++){
				if($item['picpath_'.$i]!=$picpath_ary[$i]){
					$ad_file=@upload($picpath_ary[$i],'ad',$webmaster_config);
					$ret_ary['picpath_'.$i]=$ad_file;
				} else {
					$ret_ary['picpath_'.$i]=$picpath_ary[$i];
				}
			}
			$data=array_merge($data,(array)$ret_ary);
			//upload and resize end
			$this->data->update('ca_ad',"aid='$aid'",$data);
			e_json(array('result'=>2,'aid'=>$aid),1);
		} else {
			$this->data->insert('ca_ad',$data);
			$aid=$this->db->insert_id();
			e_json(array('result'=>1,'aid'=>$aid),1);
		}
	}
	
	public function banner_img_del(){
    	$webmaster_config = $this->webmaster_config;
        $root        	  = $webmaster_config['root'];
		$num			  = (int)$this->input->post('num',true);
        $aid 	    	  = (int)$this->input->post('id',true);
        $where       	  = "aid='$aid'";
        del_img('ca_ad',$this->data,'',$where,'picpath_'.$num,$root);
        e_json('',1);
    }
}
?>